package org.openapitools.configuration;

import com.alibaba.fastjson2.JSON;
import org.openapitools.common.Result;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author xdh
 */
@Component
public class AuthorizationInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String authorizationHeader = request.getHeader("Authorization");

        if (authorizationHeader == null || authorizationHeader.isEmpty()) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            Result<String> result = Result.error("Missing Authorization header");
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(JSON.toJSONString(result));
            return false;
        }

        // 可以进一步验证token格式
        if (!authorizationHeader.startsWith("Bearer ")) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            Result<String> result = Result.error("Invalid Authorization format");
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(JSON.toJSONString(result));
            return false;
        }

        // 可以验证token有效性
        String token = authorizationHeader.substring(7);
        // "Bearer "之后的部分
        if (!isValidToken(token)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            Result<String> result = Result.error("Invalid token");
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(JSON.toJSONString(result));
            return false;
        }

        return true;
    }

    private boolean isValidToken(String token) {
        // 实现token验证逻辑
        // 示例中直接返回true
        return true;
    }
}
